package controllers

import (
	"gitee.com/tangrx/go-admin/app"
	"gitee.com/tangrx/go-admin/models"
	"gitee.com/tangrx/go-admin/utils"
	"gitee.com/tangrx/go-admin/utils/captcha"
	"gitee.com/tangrx/go-admin/utils/session"
	"github.com/gin-gonic/gin"
	"image/png"
	"log"
)

type Login struct {
	Username string `form:"username" json:"username" xml:"username"  binding:"required"`
	Password string `form:"password" json:"password" xml:"password" binding:"required"`
	Code     string `form:"code" json:"code" xml:"code" binding:"required"`
	UUID     string `form:"uuid" json:"uuid" xml:"uuid" binding:"required"`
}

func init() {
	// 验证码
	app.GET("/auth/code", func(c *gin.Context) {
		img, str := captcha.GetCaptcha(4)
		var key = c.Query("r")
		log.Println(key)
		session.SaveCode(key, str) // 保持验证码
		log.Println(str)
		png.Encode(c.Writer, img)
		//c.JSON(200, gin.H{
		//	"message": "dddd",
		//})
	})
	app.Any("/auth/login", func(c *gin.Context) {
		var json Login
		if err := c.ShouldBindJSON(&json); err != nil {
			c.JSON(200, gin.H{"error": err.Error()})
			return
		}
		if len(json.Code) == 0 {
			c.JSON(200, gin.H{"status": "100",
				"data": nil,
				"msg":  "验证码不能为空！",
			})
			return
		}
		code := session.GetCode(json.UUID)
		log.Println("code:", code)
		if code != json.Code {
			c.JSON(200, gin.H{"status": "100",
				"data": nil,
				"msg":  "验证码不正确！",
			})
			return
		}
		user := models.UserLogin(json.Username)
		if user == nil {
			c.JSON(200, gin.H{"status": "100",
				"data": nil,
				"msg":  "账号或密码错误！",
			})
			return
		}
		newPassword := utils.Md5(json.Password + user.Salt)
		log.Println(newPassword)
		log.Println(user.Userpwd)
		if user.Userpwd != newPassword {
			c.JSON(200, gin.H{"status": "101", "msg": "账号或密码错误！"})
			return
		}
		token := session.GUUID()
		err := session.SaveSession(token, &user)
		if err != nil {
			log.Fatalln("保存token错误", err)
		}
		models.Update4Login(user.Userid, c.ClientIP())
		c.JSON(200, gin.H{"status": "200",
			"token": token,
			"name":  user.Nickname,
		})
		return
	})

	// 获取用户菜单
	app.Any("/auth/menu", func(c *gin.Context) {
		userId := app.GetUserId(c)
		isSup := app.IsSuper(c)
		log.Println("是否是超级管理员：", isSup)
		if isSup {

			c.JSON(200, gin.H{"status": "200",
				"data": models.GetAllMenu(),
			})
			return
		}
		c.JSON(200, gin.H{"status": "200",
			"data": models.GetMenuByUserId(userId),
		})
		return
	})

}
